import React, { useState, useEffect } from 'react';
import { connect } from 'dva';
import { useUpdateEffect } from '@umijs/hooks';
import { Tooltip, Row, Col, Card, Form, Input, Button, Modal } from 'antd';
import dynamic from 'umi/dynamic';
import LoadingComponent from '@/components/PageLoading/index';
import SlickTable from '@/components/SlickTable';
import useSlickTableTemp from '@/hooks/useSlickTableTemp';
import request from '@/utils/request';
import styles from './styles.less';
import TacheCatalogTree from './components/TacheCatalogTree';
import Tachetab from './components/TacheTab';

const { info, success, warning } = Modal;
const FormItem = Form.Item;

const namespace = 'flowTacheConfig';

const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 8 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 16 },
  },
};

// 判断空对象
const isEmptyObject = obj => {
  if (Object.keys(obj).length === 0) {
    return true;
  }
  return false;
};

const DealModeCfg = dynamic({
  loader: () => import('./components/tacheCfgs/DealModeCfg'),
  loading: LoadingComponent,
});

const LimitTimeCfg = dynamic({
  loader: () => import('./components/tacheCfgs/LimitTimeCfg'),
  loading: LoadingComponent,
});

const StatusCfg = dynamic({
  loader: () => import('./components/tacheCfgs/StatusCfg'),
  loading: LoadingComponent,
});

const SubFlowCfg = dynamic({
  loader: () => import('./components/tacheCfgs/SubFlowCfg'),
  loading: LoadingComponent,
});

function FlowTacheConfig(props) {
  const { getFieldDecorator } = props.form;
  const [params, setParams] = useState({}); // 查询条件
  const [selectRecord, setSelectRecord] = useState({}); // 选中的行记录
  const [dealModeVisibleFlag, setDealModeVisibleFlag] = useState(false); // 设置处理模式弹窗
  const [limitTimeVisibleFlag, setLimitTimeVisibleFlag] = useState(false); // 设置时限弹窗
  const [subFlowVisibleFlag, setSubFlowVisibleFlag] = useState(false); // 设置子流程弹窗
  const [statusVisibleFlag, setStatusVisibleFlag] = useState(false); // 设置状态弹窗
  const [selectRowId, setSelectRowId] = useState(null);

  // 初始化表格数据
  const { tableProps } = useSlickTableTemp(
    { pageSize: 10 },
    'pmc/pms/pmOrderFlowNode/queryPage',
    params
  );

  useUpdateEffect(() => {
    if (isEmptyObject(props.selectRecord)) {
      setParams({
        ...params,
      });
    }
  }, [props.selectRecord]);

  // useEffect(()=>{
  //   if(!isEmptyObject(props.selectCatalog)){
  //     // request('/project/OrderFlowExecController/modifyOrderFlowExec.do',{
  //     //   data: submintData
  //     // }).then(res => {
  //     //   if (res.resultCode && res.resultCode === 'TRUE') {
  //     //       // props.setUrgeTimeCfgFlag(false);
  //     //       props.handleDealModeCallBack(false);
  //     //   } else {
  //     //     info({title: "提交失败", content: (res.resultMsg)});
  //     //   }
  //     // });
  //   }
  // },[props.selectCatalog])

  // 通过dva存当前需要传递的数据
  const saveSelectRecord = params => {
    const { dispatch } = props;
    dispatch({
      type: `${namespace}/saveSelectRecord`,
      payload: params,
    });
  };

  const initData = () => {};

  // 初始化
  useEffect(() => {
    initData();
  }, []);

  useEffect(() => {
    reloadGrid();
  }, [props.reloadFlag]);

  const handleQuery = () => {
    const formData = props.form.getFieldsValue();
    formData.pageSize = 10;
    formData.pageNum = 1;
    formData.gb_reset = true;
    setParams(formData);
  };

  const handleReset = () => {
    props.form.resetFields(); // 这是重置为默认值
  };

  // 表格选中
  const handleSelectRows = record => {
    if (record != null) {
      setSelectRecord(record);
      saveSelectRecord(record);
    } else {
      setSelectRecord({});
      saveSelectRecord({});
    }
  };

  // 刷新表格
  const reloadGrid = () => {
    setParams({
      ...params,
    });
  };

  // 处理模式模态框控制方法
  const handleDealModeVisible = visibleFlag => {
    setDealModeVisibleFlag(visibleFlag);
  };
  // 处理模式回调处理
  const handleDealModeCallBack = resData => {
    reloadGrid();
  };
  // 处理模式回调方法
  const handleDealModeCallBackMethods = {
    handleDealModeVisible,
    handleDealModeCallBack,
  };

  // 环节时限模态框控制方法
  const handleLimitTimeVisible = visibleFlag => {
    setLimitTimeVisibleFlag(visibleFlag);
  };
  // 环节时限回调处理
  const handleLimitTimeCallBack = resData => {
    reloadGrid();
  };
  // 环节时限回调方法
  const handleLimitTimeCallBackMethods = {
    handleLimitTimeVisible,
    handleLimitTimeCallBack,
  };

  // 子流程模态框控制方法
  const handleSubFlowVisible = visibleFlag => {
    setSubFlowVisibleFlag(visibleFlag);
  };
  // 子流程回调处理
  const handleSubFlowCallBack = resData => {
    reloadGrid();
  };
  // 子流程回调方法
  const handleSubFlowCallBackMethods = {
    handleSubFlowVisible,
    handleSubFlowCallBack,
  };

  // 工单状态模态框控制方法
  const handleStatusVisible = visibleFlag => {
    setStatusVisibleFlag(visibleFlag);
  };
  // 工单状态回调处理
  const handleStatusCallBack = resData => {
    reloadGrid();
  };
  // 工单状态回调方法
  const handleStatusCallBackMethods = {
    handleStatusVisible,
    handleStatusCallBack,
  };

  const checkSelectRow = () => {
    if (isEmptyObject(selectRecord)) {
      warning({ title: '请先选中一条记录' });
      return false;
    }
    return true;
  };

  // 设置环节处理模式
  const handleDealMode = () => {
    if (checkSelectRow()) {
      handleDealModeVisible(true);
    }
  };

  // 设置环节时限
  const handleLimitTime = () => {
    if (checkSelectRow()) {
      handleLimitTimeVisible(true);
    }
  };

  // 设置环节子流程
  const handleSubFlow = () => {
    if (checkSelectRow()) {
      handleSubFlowVisible(true);
    }
  };

  // 设置环节工单状态
  const handleStatus = () => {
    if (checkSelectRow()) {
      handleStatusVisible(true);
    }
  };

  const cellStyle = {
    maxWidth: 200,
    overflow: 'hidden',
    whiteSpace: 'nowrap',
    textOverflow: 'ellipsis',
    cursor: 'pointer',
  };

  const columns = [
    {
      title: '环节名称',
      dataIndex: 'flowNodeName',
      onCell: () => {
        return {
          style: cellStyle,
        };
      },
      render: text => (
        <Tooltip placement="topLeft" title={text}>
          {text}
        </Tooltip>
      ),
    },
    {
      title: '环节编码',
      dataIndex: 'flowNodeCode',
    },
    {
      title: '完成时限',
      dataIndex: 'limitValue',
    },
    {
      title: '告警时限',
      dataIndex: 'alertValue',
    },
    {
      title: '时限单位',
      dataIndex: 'timeUnitName',
    },
    {
      title: '处理模式',
      dataIndex: 'operModeName',
    },
    {
      title: '子流程ID',
      dataIndex: 'subFlowId',
    },
    {
      title: '子流程名称',
      dataIndex: 'subFlwoName',
    },
    {
      title: '工单状态',
      dataIndex: 'orderStateName',
    },
  ];

  return (
    <div className="site-card-wrapper">
      {/* <Row gutter={24}>
        <Col span={6}>
          <Card
            title="环节目录选择"
            className="cute"
          >
            <TacheCatalogTree selectRecord={selectRecord} />
          </Card>
        </Col> */}
      <Col span={24}>
        <Card
          title="环节扩展配置"
          className="cute"
          style={{ height: '60%' }}
          extra={
            <div>
              <Button
                className="margin-left"
                type="primary"
                onClick={() => {
                  handleDealMode();
                }}
              >
                设置处理模式
              </Button>
              <Button
                className="margin-left"
                type="primary"
                onClick={() => {
                  handleLimitTime();
                }}
              >
                设置环节时限
              </Button>
              <Button
                className="margin-left"
                type="primary"
                onClick={() => {
                  handleSubFlow();
                }}
              >
                设置子流程
              </Button>
              <Button
                className="margin-left"
                type="primary"
                onClick={() => {
                  handleStatus();
                }}
              >
                设置状态
              </Button>
            </div>
          }
        >
          <Form style={{ marginBottom: 10 }}>
            <Row>
              <Col span={6}>
                <FormItem label="环节编码" {...formItemLayout}>
                  {getFieldDecorator('flowNodeCode')(<Input />)}
                </FormItem>
              </Col>
              <Col span={6}>
                <FormItem label="环节名称" {...formItemLayout}>
                  {getFieldDecorator('flowNodeName')(<Input />)}
                </FormItem>
              </Col>
            </Row>
            <div style={{ textAlign: 'center' }}>
              <Button type="primary" className="margin-right" onClick={handleQuery}>
                查询
              </Button>
              <Button type="default" onClick={handleReset}>
                重置
              </Button>
            </div>
          </Form>
          <SlickTable
            rowKey={record => record.flowNodeId}
            columns={columns}
            {...tableProps}
            scroll={{ x: 'max-content' }}
            rowClassName={record => {
              return record.flowNodeId === selectRowId ? styles.clickRowStyle : '';
            }}
            onRow={record => {
              return {
                onClick: () => {
                  setSelectRowId(record.flowNodeId);
                  handleSelectRows(record);
                },
              };
            }}
          />
        </Card>
        <Card className="cute">
          <Tachetab />
        </Card>
        {dealModeVisibleFlag ? (
          <DealModeCfg
            selectRecord={selectRecord}
            {...handleDealModeCallBackMethods}
            modalVisible={dealModeVisibleFlag}
          />
        ) : null}
        {limitTimeVisibleFlag ? (
          <LimitTimeCfg
            selectRecord={selectRecord}
            {...handleLimitTimeCallBackMethods}
            modalVisible={limitTimeVisibleFlag}
          />
        ) : null}
        {subFlowVisibleFlag ? (
          <SubFlowCfg
            selectRecord={selectRecord}
            {...handleSubFlowCallBackMethods}
            modalVisible={subFlowVisibleFlag}
          />
        ) : null}
        {statusVisibleFlag ? (
          <StatusCfg
            selectRecord={selectRecord}
            {...handleStatusCallBackMethods}
            modalVisible={statusVisibleFlag}
          />
        ) : null}
      </Col>
      {/* </Row> */}
    </div>
  );
}

export default connect(({ flowTacheConfig, setting }) => ({
  reloadFlag: flowTacheConfig.reloadFlag,
  selectCatalog: flowTacheConfig.selectCatalog,
  size: setting.size,
}))(Form.create()(FlowTacheConfig));
